﻿@implements IDisposable
@inject GlobalConfig GlobalConfig;

<MSnackbar @bind-Value="Show" Color="white" Top > @*TimeOut=@TimeOut*@
    <ChildContent>
        @{
            var (icon, color) = GetMessageIconInfo();
        }
        <MIcon Color="@color" Size=18>@icon</MIcon>
        <span class="text-caption neutral--text ml-1">@Message</span>
    </ChildContent>
    <ActionContent>
        <MIcon Color="neutral-lighten-3" Size=18 OnClick="Close">mdi-close</MIcon>
    </ActionContent>
</MSnackbar>

@code{
    [Parameter]
    public bool Show { get; set; }

    [Parameter]
    public EventCallback<bool> ShowChanged { get; set; }

    [Parameter]
    public string? Message { get; set; }

    [Parameter]
    public int Timeout { get; set; } = 2000;

    [Parameter]
    public MessageTypes MessageType { get; set; }

    async Task Close()
    {
        Show = false;

        if (ShowChanged.HasDelegate)
        {
            await ShowChanged.InvokeAsync(false);
        }
    }

    public void ShowMessage(string message,MessageTypes messageType,int timeout)
    {
        Show = true;
        Message = message;
        MessageType = messageType;
        Timeout = timeout;

        base.StateHasChanged();
    }

    (string icon,string color) GetMessageIconInfo()
    {
        return MessageType switch
        {
            MessageTypes.Information => ("mdi-information", "info"),
            MessageTypes.Success => ("mdi-check-circle", "success"),
            MessageTypes.Error => ("mdi-alert-circle-outline", "error"),
            _ => ("mdi-alert-outline", "warning")
        };
    } 

    protected override void OnInitialized()
    {
        GlobalConfig.OnMessageChanged += ShowMessage;
    }

    public void Dispose()
    {
        GlobalConfig.OnMessageChanged -= ShowMessage;
    }
}
